<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      title="部门列表"
      toolbar
      search
      ref="asyncExpandTreeRef"
      :clickRowToExpand="false"
      defaultExpandAll
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, nextTick, onMounted, ref, unref } from 'vue';

  import { BasicTree, TreeItem, TreeActionType } from '@/components/Tree';
  import { getDeptList } from '@/api/system/dept';

  export default defineComponent({
    name: 'DeptTree',
    components: { BasicTree },

    emits: ['select'],
    setup(_, { emit }) {
      const treeData = ref<TreeItem[]>([]);
      const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
      async function fetch() {
        const treeapidata = await getDeptList(null);
        var dept_data = treeapidata.data;
        dept_data = await convertKey(dept_data);
        console.log('dept_data', dept_data);
        treeData.value = dept_data as any as TreeItem[];
        nextTick(() => {
          unref(asyncExpandTreeRef)?.expandAll(true);
        });
      }

      function handleSelect(keys) {
        emit('select', keys[0]);
      }
      async function convertKey(menulist) {
        if (!menulist) return null;
        for (const map of menulist) {
          map['title'] = map.name;
          map['key'] = map.id;
          // map['icon'] = map.icon
          if (map.children != undefined && map.children.length > 0) {
            var childrenList = await convertKey(map.children);
            map['children'] = childrenList;
          }
        }
        return menulist;
      }
      onMounted(() => {
        fetch();
      });
      return { treeData, handleSelect, asyncExpandTreeRef };
    },
  });
</script>
